# -*- coding: utf-8 -*-
"""
------------------------------------------------------------------------------
    File Name:  multiprocessing_demo
    Author   :  wanwei1029
    Date     :  2018-10-18
    Desc     :
------------------------------------------------------------------------------
"""
import multiprocessing
import time
import random
import os


class MulitProcessObj(multiprocessing.Process):
    def run(self):
        time.sleep(5)
        print("my name is {0}".format(self.name))


def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 30)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))


def test_pool():
    print('Parent process %s.' % os.getpid())
    p = multiprocessing.Pool(15)
    for i in range(15):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')


def demo():
    jobs = []
    for i in range(5):
        p = MulitProcessObj()
        jobs.append(p)
        p.start()
    for j in jobs:
        j.join()
    # time.sleep(10)


if __name__ == '__main__':
    test_method = "demo"
    if test_method == "demo":
        for i in range(5):
            p = MulitProcessObj()
            p.start()
        demo()
    elif test_method == "test_pool":
        test_pool()
    print("all done")
